<template>
  <dialog-form
    ref="dialogForm"
    width="640px"
    :title="title"
    :visible="visible"
    :form-attrs="{formData: modalFormData, renderFormItem, formButtons, labelWidth: '100px'}"
    @close="hanleClose"
  />
</template>

<script>
import { mapGetters } from 'vuex'
import { fetchDropDeviceList } from '@/api/common/commonDropDown'
import { DialogForm } from '@/components'
import { modalFormItem, formButtons } from './config'

export default {
  name: 'CarUpdate',
  components: { DialogForm },
  props: {
    title: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      deviceDropList: [], // 设备下拉数据

      modalFormData: {},
      renderFormItem: [],
      formButtons: formButtons(this.handleModalSubmit, this.hanleClose)
    }
  },
  computed: {
    ...mapGetters(['accountCascadeList'])
  },
  watch: {
    visible() {
      if (this.visible) {
        const orgId = this.modalFormData.orgId
        this.postDropDeviceList(orgId)
        this.$store.dispatch('dropDown/postAccountCascade', orgId)
      }
    },
    accountCascadeList() {
      this._createFormItem()
    }
  },
  methods: {
    handleModalSubmit(values) {
      values.deviceIdStr = values.deviceIdList.join(',')
      values.accountIdStr = (values.accountIdList.map(item => item[1])).join(',')
      this.$emit('handleModalSubmit', values)
    },

    hanleClose() {
      this.$emit('update:visible', false)
    },

    _createFormItem() { // 创建 formItem
      this.renderFormItem = modalFormItem(this.deviceDropList, this.accountCascadeList)
    },

    postDropDeviceList(orgId) { // 获取设备下拉
      fetchDropDeviceList({ orgId, bindType: 2 }).then(res => {
        this.deviceDropList = res.map(item => ({ key: item.id + '', value: item.name }))
        this._createFormItem()
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
